<template>
    <div>
        <div id="searchData">
            <el-form :inline="true" :model="searchForm" class="demo-form-inline">
                <el-form-item>
                    <el-input v-model="searchForm.productName" placeholder="——请按照商品名称搜索——"
                        class="center-text"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="success" @click="search" icon="el-icon-search">搜索</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="addProduct" icon="el-icon-circle-plus-outline">添加</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="refresh" icon="el-icon-refresh">刷新</el-button>
                </el-form-item>
            </el-form>

        </div>

        <!-- table -->
        <el-table :data="tableData" style="width: 100%" height="450">
            <!-- 序号 -->
            <el-table-column type="index" :index="indexMethod"></el-table-column>
            <el-table-column prop="name" label="商品类型" width="120">
            </el-table-column>
            <el-table-column prop="productName" label="商品名称" width="120">
            </el-table-column>
            <el-table-column prop="picture" label="头像" width="100">
                <template v-slot="scope">
                    <el-image style="width: 60px; height: 40px" :src="scope.row.picture">
                    </el-image>
                </template>
            </el-table-column>
            <el-table-column prop="newPrice" label="现价(元)" width="120">
            </el-table-column>
            <el-table-column prop="loadPrice" label="原价(元)" width="120">
            </el-table-column>
            <el-table-column prop="integral" label="积分" width="100">
            </el-table-column>
            <el-table-column prop="monthlySales" label="月销售额(元)" width="120">
            </el-table-column>
            <el-table-column prop="freight" label="运费(元)" width="100">
            </el-table-column>
            <el-table-column prop="storeName" label="门店" width="100">
            </el-table-column>
            <el-table-column prop="isline" label="是否上线" :formatter="isline" width="100">
            </el-table-column>
            <el-table-column prop="prompt" label="温馨提示" width="300">
            </el-table-column>
            <el-table-column prop="productDetails" label="商品详情" width="150" :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column prop="userName" label="创建人" width="120" :formatter="createFormatter">
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="160">
            </el-table-column>
            <el-table-column prop="userName" label="更新人" width="120" :formatter="updateFormatter">
            </el-table-column>
            <el-table-column prop="updateTime" label="更新时间" width="160">
            </el-table-column>
            <el-table-column prop="remark" label="备注" width="120">
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
                <template slot-scope="scope">
                    <el-button size="small" type="primary" icon="el-icon-edit-outline"
                        @click="updataProduct(scope.row)">编辑
                    </el-button>
                    <el-button size="small" type="danger" @click="deleteproduct(scope.row.productId)"
                        icon="el-icon-remove-outline">删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--分页功能-->
        <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="searchForm.currentPage"
                :page-sizes="[1,2,5,10]"
                :page-size="searchForm.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
        </el-pagination>

        <!--添加或者更新的form表单-->
        <div id="dialog">
            <!--添加和编辑的对话框-->
            <el-dialog :visible.sync="dialogFormVisible" :before-close="handleClose">
                <el-form ref="addEditform" :rules="rules" :model="addEditform">
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="商品类型" :label-width="formLabelWidth" prop="proTypeId">
                                <div class="left">
                                    <el-select v-model="addEditform.proTypeId" clearable placeholder="请选择商品类型"
                                        style="width: 100%">
                                        <el-option v-for="item in optionsProductType" :label="item.name"
                                            :value="item.commentId">
                                        </el-option>
                                    </el-select>
                                </div>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-form-item label="所属门店" :label-width="formLabelWidth" prop="storeId">
                        <div class="left">
                            <el-select v-model="addEditform.storeId" clearable placeholder="请选择所属门店"
                                style="width: 100%">
                                <el-option v-for="item in stores" :label="item.storeName" :value="item.storeId">
                                </el-option>
                            </el-select>
                        </div>
                    </el-form-item>
                    <el-form-item label="商品名称" :label-width="formLabelWidth" prop="productName">
                        <div class="left">
                            <el-input v-model="addEditform.productName" autocomplete="off"
                                placeholder="商品名称"></el-input>
                        </div>
                    </el-form-item>

                    <el-form-item label="商品封面图片" :label-width="formLabelWidth" prop="picture">
                        <el-upload class="avatar-uploader" :action="uploadAction" :headers="head"
                            :show-file-list="false" :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload">
                            <img v-if="addEditform.picture" :src="addEditform.picture" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="积分" :label-width="formLabelWidth" prop="integral">
                                <div class="left">
                                    <el-input v-model="addEditform.integral" autocomplete="off"
                                        placeholder="设置获取商品所需积分"></el-input>
                                </div>
                            </el-form-item>
                        </el-col>
                        <el-col :span="10">
                            <el-form-item label="是否启用积分" :label-width="formLabelWidth">
                                <div class="left">
                                    <el-switch v-model="addEditform.integralEnabled" class="isShow" :active-value="'0'"
                                        :inactive-value="'1'" active-color="#13ce66" inactive-color="#ff4949">
                                    </el-switch>
                                </div>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="原价(元)" :label-width="formLabelWidth" prop="loadPrice">
                                <div class="left">
                                    <el-input v-model="addEditform.loadPrice" autocomplete="off"
                                        placeholder="请输入该商品原价"></el-input>
                                </div>
                            </el-form-item>
                        </el-col>
                        <el-col :span="10">
                            <el-form-item label="所需金额(元)" :label-width="formLabelWidth" prop="newPrice">
                                <div class="left">
                                    <el-input v-model="addEditform.newPrice" autocomplete="off"
                                        placeholder="金额(元)"></el-input>
                                </div>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="运费(元)" :label-width="formLabelWidth" prop="freight">
                                <div class="left">
                                    <el-input v-model="addEditform.freight" autocomplete="off"
                                        placeholder="设置该商品的所需运费"></el-input>
                                </div>
                            </el-form-item>
                        </el-col>
                        <!--                        <el-col :span="10">-->
                        <!--                            <el-form-item label="是否包邮" :label-width="formLabelWidth">-->
                        <!--                                <div class="left">-->
                        <!--                                    <el-switch-->
                        <!--                                            v-model="addEditform.isFreightShipping"-->
                        <!--                                            class="isShow"-->
                        <!--                                            :active-value="'0'"-->
                        <!--                                            :inactive-value="'1'"-->
                        <!--                                            active-color="#13ce66"-->
                        <!--                                            inactive-color="#ff4949"-->
                        <!--                                    >-->
                        <!--                                    </el-switch>-->
                        <!--                                </div>-->
                        <!--                            </el-form-item>-->
                        <!--                        </el-col>-->
                    </el-row>

                    <el-form-item label="温馨提示" :label-width="formLabelWidth">
                        <div class="left">
                            <el-input v-model="addEditform.prompt" autocomplete="off"
                                placeholder="请编辑该商品的提示信息"></el-input>
                        </div>
                    </el-form-item>
                    <el-form-item label="商品备注" :label-width="formLabelWidth">
                        <div class="left">
                            <el-input v-model="addEditform.remark" autocomplete="off" placeholder="请输入备注"></el-input>
                        </div>
                    </el-form-item>
                    <!--富文本编辑器-->
                    <el-form-item label="商品详情" :label-width="formLabelWidth">
                        <!--                        <div id="editor"></div>-->
                        <div id="editor" v-model="addEditform.productDetails">
                        </div>
                        <!--                        <div id="editor" style="text-align: left"></div>-->
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="enterAdd" v-if="actor==='add'">确定添加</el-button>
                    <el-button type="primary" @click="enterEdit" v-if="actor==='edit'">确定编辑</el-button>
                  </span>
            </el-dialog>
        </div>

    </div>
</template>
<script>
//引入富文本样式
import E from "wangeditor"

export default {
    name: "Product",
    data() {
        return {
            searchForm: {
                currentPage: 1, //当前页数
                pageSize: 5,//每页的数量
            },
            total: 0, //总options条数
            tableData: [],

                //加载更新人（不能用undefined）报错；
                Options: [],
                dialogFormVisible: false,
                //添加的数据
                form: {},
                //添加选宽的宽度
                formLabelWidth: "120px",
                rules: {
                    storeId: [{required: true, message: '商店不能为空', trigger: 'change'}],
                    picture: [{required: true, message: '图片不能为空', trigger: 'change'}],
                    proTypeId: [{required: true, message: '商品类型不能为空', trigger: 'change'}],
                    productName: [{required: true, message: '商品名称不能为空', trigger: 'change'}],
                    integral: [{required: true, message: '积分不能为空', trigger: 'change'}],
                    loadPrice: [{required: true, message: '原价不能为空', trigger: 'change'}],
                    newPrice: [{required: true, message: '现价不能为空', trigger: 'change'}],
                    freight: [{required: true, message: '运费不能为空', trigger: 'change'}],
                },
                addEditform: {
                    productId: '',
                    storeId: '',
                    picture: '',
                    proTypeId: '',
                    commentId: '',
                    productName: '',
                    integral: '',
                    integralEnabled: '',
                    loadPrice: '',
                    newPrice: '',
                    freight: '',
                    isFreightShipping: '',
                    prompt: '',
                    remark: '',
                },
                //获取修改商品类型
                optionsProductType: [],
                //获取修改商店名称
                optionsStore: [],
                //确认按钮类型
                actor: '',
                //上传图片访问路径
                uploadAction: this.$http.getUri() + "/product/list/uploadFile",
                //图片参数
                head: '',
                stores: [],
                editor: null,//富文本默认值s
            }
        },
        created() {
            //加载更新人和创建人
            this.loadUpdateBy();
            this.selectData();
            this.loadStoreMsg();
            this.loadProductTypeMsg();
            this.head = {
               token: sessionStorage.getItem("token")
            }
        },
        methods: {
            //加载商品类型信息
            loadProductTypeMsg() {
                this.$http.get("/product/type/selectAllProductType").then(resp => {
                    this.optionsProductType = resp.data.data;
                })
            },
            //分页查询
            selectData() {
                this.$http.post("/product/list/select", this.searchForm).then(result => {
                    //console.log("选哟的", result)
                    this.tableData = result.data.data.records;
                    this.total = result.data.data.total;
                })
            },

            //获取所有的用户更新人和创建人
            loadUpdateBy() {
                this.$http.get("/system/user/selectAll").then(result => {
                    this.Options = result.data.data;
                })
            }
            ,
            //从查到的用户信息中查询对应的创建者姓名
            createFormatter(row) {
                for (let i = 0; i < this.Options.length; i++) {
                    if (row.createId === this.Options[i].userId) {
                        return this.Options[i].userName;
                    }
                }
            }
            ,
            //从查到的用户信息中查询对应的修改者姓名
            updateFormatter(row) {
                for (let i = 0; i < this.Options.length; i++) {
                    if (row.updateId === this.Options[i].userId) {
                        return this.Options[i].userName;
                    }
                }
            },

            //加载店铺信息
            loadStoreMsg() {///store/feign/selectStoreByUserId
                this.$http.get("product/list/selectStore").then(resp => {
                    this.stores = resp.data.data;
                })
            },
            //是否上线
            isline(row) {
                return row.isline === 0 ? "是" : "否";
            },

            //添加按钮的方法
            addProduct() {
                this.actor = "add";
                this.dialogFormVisible = true;
                //用时钟方法创建编辑器
                this.$nextTick(() => {
                    this.editor = new E("#editor");//管理#editor
                    this.editor.config.uploadImgServer = this.$http.getUri() + "/product/list/uploadFile";//上传文件的接口路径
                    this.editor.config.uploadFileName = "file";//指定上传的类型
                    this.editor.config.uploadImgHeaders = {
                        token: sessionStorage.getItem("token"),
                    }
                    this.editor.config.uploadImgParams = {
                        type: "img",
                    }
                    this.editor.config.uploadVideoServer = this.$http.getUri() + "/product/list/uploadFile";//上传文件的接口路径
                    this.editor.config.uploadVideoHeaders = {
                        token: sessionStorage.getItem("token"),
                    }
                    this.editor.config.uploadVideoParams = {
                        type: "video",
                    }
                    this.editor.config.uploadVideoName = "file"
                    this.editor.create();//创建编辑器
                })
            },

            //确认添加方法
            enterAdd() {
                this.$refs.addEditform.validate((valid) => {
                    console.log(valid);
                    if (valid) {
                        this.actor = ''
                        this.addEditform.productDetails = this.editor.txt.html();
                        this.$http.post("/product/list/insertProduct", this.addEditform).then(resp => {
                            console.log("添加的内容",resp)
                            if (resp.data.code === 200) {
                                this.$message({
                                    type: 'success',
                                    message: '添加成功!',
                                });
                                this.selectData();
                            }
                        },errorMsg=>{
                            this.$message({
                                type: 'warning',
                                message: '添加失败!',
                            });
                        })
                        this.addEditform = {}
                        this.dialogFormVisible = false;
                        this.editor.destroy();//销毁编辑器，用完一定要销毁，不然不会消失一直存在
                        this.editor = null;
                    }
                })
            },

            //对话框的叉叉
            handleClose() {
                this.dialogFormVisible = false;
                this.addEditform = {};
                this.editor.destroy();//销毁编辑器，用完一定要销毁，不然不会消失一直存在
                this.editor = null;
                this.actor = null;
            }
            ,
            //编辑按钮
            updataProduct(row) {
                this.actor = "edit"
                this.dialogFormVisible = true;
                this.addEditform.productId = row.productId
                this.addEditform = row;
                this.addEditform.productDetails = row.productDetails;
                //用时钟方法创建编辑器
                this.$nextTick(() => {
                    this.editor = new E("#editor");//管理#editor
                    //上传图片
                    this.editor.config.uploadImgServer = this.$http.getUri() + "/product/list/uploadFile";//上传文件的接口路径
                  //console.log("编辑的内容",this.editor.config.uploadImgServer.data()+"~~~~~~~~~~~~~~~!!!!!!!!")
                  this.editor.config.uploadFileName = "file";//指定上传的类型
                    this.editor.config.uploadImgHeaders = {
                        token: sessionStorage.getItem("token"),
                    }
                    //设置参数类型名字
                    this.editor.config.uploadImgParams = {
                        type: "img",
                    }
                    //上传视频
                    this.editor.config.uploadVideoServer = this.$http.getUri() + "/product/list/uploadFile";//上传文件的接口路径/aboutus/api/uploadFile
                    //给token访问后端
                    this.editor.config.uploadVideoHeaders = {
                        token: sessionStorage.getItem("token"),
                    }
                    //设置参数类型名字
                    this.editor.config.uploadVideoParams = {
                        type: "video",
                    }
                    this.editor.config.uploadVideoName = "file"
                    this.editor.create();//创建编辑器
                    //
                    this.editor.txt.html(row.productDetails);//给编辑器修改内容

                })
            }
            ,
            //确认编辑方法
            enterEdit() {
                this.$refs.addEditform.validate((valid) => {
                    //console.log(valid);
                    if (valid) {
                        this.actor = "";
                        this.addEditform.productDetails = this.editor.txt.html();
                      console.log("编辑的内容",this.addEditform+">>>>>>>>>>>>>");
                      this.$http.post("/product/list/updateProduct", this.addEditform).then(resp => {
                            if (resp.data.code === 200) {
                                this.$message({
                                    type: 'success',
                                    message: '更新成功!'
                                });
                                this.selectData();
                            }
                        },errorMsg => {
                            this.$message({
                                type: 'warning',
                                message: '更新失败!'
                            });
                        })
                        this.addEditform = {}
                        this.editor.destroy();//销毁编辑器，用完一定要销毁，不然不会消失一直存在
                        this.editor = null;
                        this.dialogFormVisible = false;
                    }
                })

            },
            // })


        //取消按钮
        cancelbutt() {
            this.dialogFormVisible = false
            this.addEditform = {};
            this.selectData();
            this.editor.destroy();//销毁编辑器，用完一定要销毁，不然不会消失一直存在
            this.editor = null;
        }
        ,

        //判断运费
        getfreight(row) {
            if (row.isFreightShipping === 0) {
                row.freight = "";
                return "包邮";
            } else {
                return "元";
            }
        }
        ,

        //图片上传的方法
        handleAvatarSuccess(res, file) {
              //console.log(res+"图片的地址！！！！！！！！！");
            this.addEditform.picture = res.data

        }
        ,
        beforeAvatarUpload(file) {
            const isImage = file.type.startsWith('image/');
            const isJPGorPNG = isImage && (file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/webp');
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPGorPNG) {
                this.$message.error('上传头像图片只能是 JPG或者是PNG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPGorPNG && isLt2M;
        },


        //开关组件更新数据库状态 是否有效
        changeSwitch(data) {

        },
        //查询商品
        search() {
            this.selectData();
        }
        ,
        //每页数量发生变化
        handleSizeChange(val) {
            this.searchForm.pageSize = val;
            this.selectData();
        }
        ,
        //页码发生变化
        handleCurrentChange(val) {
            this.searchForm.currentPage = val;
            this.selectData();
        }
        ,
        //刷新方法
        refresh() {
            // location.reload();
            this.searchForm = {};
            this.searchForm.productName = "";
            this.searchForm.currentPage = 1;
            this.searchForm.pageSize = 5;
            this.selectData();
        }
        ,
        // //删除数据
        deleteproduct(productId) {
            this.$confirm('是否删除该数据？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$http.get("/product/list/deleteByProductId?productId=" + productId).then(resp => {
                    if (resp.data.code === 200) {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        this.searchForm.currentPage = 1;
                        this.selectData();
                    }
                },errorMsg => {
                    this.$message({
                        type: 'warning',
                        message: '删除失败!'
                    });
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        }
        ,

        //显示索引
        indexMethod(index) {
            return index + 1;
        }
        ,
        //审核状态
        isExamine(row) {
            if (row.examineStatus === 0) {
                return "未审核";
            } else if (row.examineStatus === 1) {
                return "审核通过";
            } else {
                return "审核未通过";
            }
        }
        ,

    }
}
</script>

<style scoped>
/*上传图片的样式*/
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    align-items: center;
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 100px;
    padding-top: 78px;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.left {
    /* 设置弹出框中输入框的宽度和位置 */
    width: 87%;
    text-align: left;
}
</style>